package com.vaadin.thomas.contenttool.ui;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;

import com.vaadin.terminal.ClassResource;
import com.vaadin.terminal.Resource;
import com.vaadin.terminal.Sizeable;
import com.vaadin.thomas.contenttool.Config;
import com.vaadin.thomas.contenttool.ContentTool;
import com.vaadin.thomas.contenttool.data.Value;
import com.vaadin.thomas.contenttool.data.Version;
import com.vaadin.ui.Embedded;

public class Util {

	public static Embedded getFlag(String locale) {
		Embedded e = new Embedded(null, getResource("flags/" + locale));
		e.setWidth(16, Sizeable.UNITS_PIXELS);
		e.setHeight(11, Sizeable.UNITS_PIXELS);
		e.addStyleName("flag");
		return e;
	}

	public static Embedded getIcon(String icon) {
		Embedded e = new Embedded(null, getResource("icons/" + icon));
		e.setWidth(16, Sizeable.UNITS_PIXELS);
		e.setHeight(16, Sizeable.UNITS_PIXELS);
		e.addStyleName("icon");
		return e;
	}

	public static Resource getResource(String res) {
		return new ClassResource(ContentTool.class, "widgetset/public/" + res
				+ ".png", AdminMainLayout.app());
	}

	public static String parseVersion(Version v) {

		if (v.isPreview()) {
			return AdminMainLayout.ct().get(
					"contenttool.content.oldversions.version-preview");
		} else if (v.isProduction()) {
			return AdminMainLayout.ct().get(
					"contenttool.content.oldversions.version-production");
		}

		return AdminMainLayout.ct().get(
				"contenttool.content.oldversions.version")
				+ " " + v.getVersionNumber();
	}

	public static void filterCTIdentifiers(List<Value> vals,
			boolean showContentToolIdentifiers) {
		if (!showContentToolIdentifiers) {
			Set<Value> toRemove = new HashSet<Value>();
			for (Value v : vals) {
				if (v.getKey().startsWith("contenttool")) {
					toRemove.add(v);
				}
			}
			vals.removeAll(toRemove);
		}
	}

	/**
	 * Return the value with newlines replaced as HTML-tags.
	 */
	public static String asHTML(String val) {
		val = val.replaceAll("\r\n", "<br/>");
		val = val.replaceAll("\r", "<br/>");
		val = val.replaceAll("\n", "<br/>");
		return val;
	}

	public static void log(String msg, Level level, Config conf) {

		if (conf == null) {
			System.out.println(level.getName() + ": " + msg);

		} else if (conf.allowLogging()) {

			if (!conf.debug() && Level.FINE == level) {
				// ignore
			} else if (conf.logger() != null) {
				conf.logger().log(level, msg);
			} else {
				System.out.println(level.getName() + ": " + msg);
			}
		}
	}
}
